package com.example.work;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.Spanned;
import android.text.TextWatcher;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MainActivity extends AppCompatActivity {

    private EditText userName;
    private EditText passWord;
    private EditText name;
    private Button RegBtn;
    private Spinner sex;
    public String imgDate;
    public String code_img;

    Handler handler = new Handler()
    {
        public void handleMessage(Message msg)
        {
            if (msg.what == 0x123)
            {
            }
            else
            {
                Toast.makeText(MainActivity.this,
                        "网络错误", Toast.LENGTH_LONG)
                        .show();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        userName = (EditText) findViewById(R.id.userName);
        passWord = (EditText) findViewById(R.id.passWord);
        RegBtn = (Button) findViewById(R.id.btn_Login);
        name = (EditText) findViewById(R.id.name);
        sex = (Spinner) findViewById(R.id.sex_select);
        RegBtn.setEnabled(false);
        RegBtn.setBackgroundColor(Color.parseColor("#BBBBBB"));
        passWord.addTextChangedListener(editclick);
    }

    public  void  fileSelect(View view){
        Intent intent = new Intent();
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
        } else {
            intent.setAction(Intent.ACTION_GET_CONTENT);
        }
        intent.setType("image/*");
        startActivityForResult(intent, 1000);//打开相册
    }

    public  void  code_upload(View view){
        Intent intent = new Intent();
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
        } else {
            intent.setAction(Intent.ACTION_GET_CONTENT);
        }
        intent.setType("image/*");
        startActivityForResult(intent, 500);//打开相册
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {//相册的调用回调
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1000) {//判断是否是我们通过photo()发起的
            if (resultCode == Activity.RESULT_OK && null != data) {
                Uri uri = data.getData();
                ContentResolver cr = this.getContentResolver();
                try {
                    Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));//获取位图
                    //将位图转为字节数组后再转为base64
                    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
                    //发起网络请求，传入base64数据
                    imgDate = String.valueOf(Base64.encodeToString(outputStream.toByteArray(), Base64.NO_WRAP));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        else if (requestCode == 500) {//判断是否是我们通过photo()发起的
            if (resultCode == Activity.RESULT_OK && null != data) {
                Uri uri = data.getData();
                ContentResolver cr = this.getContentResolver();
                try {
                    Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));//获取位图
                    //将位图转为字节数组后再转为base64
                    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
                    //发起网络请求，传入base64数据
                    code_img = String.valueOf(Base64.encodeToString(outputStream.toByteArray(), Base64.NO_WRAP));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public void onClick(View v) {new Thread(new Runnable(){
        @Override
        public void run() {
            String username = userName.getText().toString().trim();
            String password = passWord.getText().toString().trim();
            String nameStr = name.getText().toString().trim();
            if(username.isEmpty()||password.isEmpty()||nameStr.isEmpty())
            {
                Looper.prepare();
                Toast.makeText(MainActivity.this,
                        "账户名或密码或姓名为空", Toast.LENGTH_LONG)
                        .show();
                Looper.loop();
                return;
            }
            else if (code_img==null||imgDate==null){
                Looper.prepare();
                Toast.makeText(MainActivity.this,
                        "图片未正常上传", Toast.LENGTH_LONG)
                        .show();
                Looper.loop();
                return;
            }
            Map<String, Object> map = new HashMap<>();
            map.put("usr", username);
            map.put("pwd", password);
            map.put("name", nameStr);
            map.put("sex", sex.getSelectedItem().toString());
            map.put("head_img",imgDate);
            map.put("code_img",code_img);
            map.put("method", "register");
            String mapJson = JSON.toJSONString(map);
            String h = "http://47.113.221.82/DianZong/servelt:8080" +
                    "";
            URL netUrl = null;
            try {
                netUrl = new URL(h);
                String content = String.valueOf(mapJson);
                HttpURLConnection conn = (HttpURLConnection) netUrl.openConnection();
                conn.setDoOutput(true);// 设置允许输出
                conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
                conn.setRequestMethod("POST");// 大写
                OutputStream outputStream = conn.getOutputStream();
                outputStream.write(content.getBytes());
                if (conn.getResponseCode() == 200) {
                    handler.sendEmptyMessage(0x123);
                    InputStreamReader reader = new InputStreamReader(conn.getInputStream(), "utf-8");
                    BufferedReader br = new BufferedReader(reader);
                    String result = new String(br.readLine().getBytes());
                    Looper.prepare();
                    if (result.equals("RegisterOk")) {
                        Toast.makeText(MainActivity.this,
                                "Register OK", Toast.LENGTH_LONG)
                                .show();
                        Intent intent=new Intent(MainActivity.this,login.class);
                        startActivity(intent);
                    }
                    else
                        Toast.makeText(MainActivity.this,
                                "Register Failed", Toast.LENGTH_LONG)
                                .show();
                    Looper.loop();
                }
                else {
                    handler.sendEmptyMessage(0x122);
                }
            } catch (MalformedURLException | ProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }).start();
    }

    private TextWatcher editclick = new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {


        }


        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {


        }

        //一般我们都是在这个里面进行我们文本框的输入的判断，上面两个方法用到的很少
        @Override
        public void afterTextChanged(Editable s) {
            String pwd = passWord.getText().toString();
            Pattern p = Pattern.compile("^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{3,16}$");
            Matcher m = p.matcher(pwd);
            if (m.matches()) {
                RegBtn.setEnabled(true);
                RegBtn.setBackgroundColor(Color.parseColor("#04BE02"));
            } else {
                RegBtn.setEnabled(false);
                RegBtn.setBackgroundColor(Color.parseColor("#BBBBBB"));
            }
        }
    };

}